import 'dart:io';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:path/path.dart' as path;

class CustomCacheManager extends CacheManager {
  static const key = 'custom-cache-key';
  static final String _cachePath = path.join('D:', 'custom_image_cache');
  static final CustomCacheManager _instance = CustomCacheManager._();

  factory CustomCacheManager() => _instance;

  CustomCacheManager._()
      : super(Config(
          key,
          stalePeriod: const Duration(days: 7),
          maxNrOfCacheObjects: 1000,
          fileService: HttpFileService(),
          fileSystem: IOFileSystem(_cachePath),
        ));

  // 直接在构造函数中使用IOFileSystem指定了缓存路径
  // 确保D盘缓存目录存在
  static void ensureCacheDirExists() {
    final cacheDir = Directory(_cachePath);
    if (!cacheDir.existsSync()) {
      cacheDir.createSync(recursive: true);
    }
  }

  static void deleteCacheDir() {
    final cacheDir = Directory(_cachePath);
    if (cacheDir.existsSync()) {
      // 判断目录的大小，超过100M时才删除
      final size = cacheDir.listSync().fold<int>(
            0,
            (previousValue, element) => previousValue + element.statSync().size,
          );
      if (size < 100 * 1024 * 1024) {
        return;
      }
      cacheDir.deleteSync(recursive: true);
    }
  }

  static void clearCache() {
    final cacheDir = Directory(_cachePath);
    if (cacheDir.existsSync()) {
      cacheDir.deleteSync(recursive: true);
    }
  }

  static Future<double> fileSize() {
    final cacheDir = Directory(_cachePath);
    double filesize = 0;
    if (cacheDir.existsSync()) {
      int size = cacheDir.listSync().fold<int>(
            0,
            (previousValue, element) => previousValue + element.statSync().size,
          );
      filesize = size / 1024 / 1024;
    } else {
      filesize = 0;
    }
    // 保留两位小数
    filesize = double.parse(filesize.toStringAsFixed(2));
    return Future.value(filesize);
  }
}
